<template>
  <a-card class="layout-card">
    <a-row align="middle" justify="space-between">
      <a-col>
        <a-button
          class="mr-8px"
          :disabled="Data.statuTypeBloon"
          type="primary"
          @click="$router.back()"
        >
          返回
        </a-button>
        <a-button :disabled="Data.statuTypeBloon" type="primary" @click="releaseFun()">
          还原全部修改
        </a-button>
        <a-button class="mx-8px" type="primary" @click="releaseSetBreakTest">
          应用试题结构
        </a-button>

        试卷原始总分：{{ Data.originalScore }};
        <span :class="Data.totalScore != Data.originalScore ? 'text-red-500' : ''">
          当前总分： {{ Data.totalScore }}
        </span>
        <label class="ml-30px text-red-500">注：</label>
        <span class="!pr-5 text-red-500">
          “&nbsp;&nbsp;<a-tag color="red"> &nbsp;</a-tag>” 已修改 {{ Data.updateNunber }} 题
        </span>
        <span class="!pr-5 text-blue-500">
          “&nbsp;&nbsp;<a-tag color="blue"> &nbsp;</a-tag>” 已新增 {{ Data.saveNunber }} 题
        </span>
        <span class="!pr-5 text-gray-400">
          “&nbsp;&nbsp;<a-tag color="rgb(193 193 193)"> &nbsp;</a-tag>” 已删除
          {{ Data.delNunber }} 题
        </span>
      </a-col>
    </a-row>

    <div class="claserbox">
      <a-row align="middle">
        <a-col :span="8">
          <div class="infobox">
            <div class="treebox mb-2" ref="treeReefbox">
              <a-tree
                :tree-data="list || []"
                :fieldNames="{ children: 'children', title: 'tmbt', key: 'id' }"
                :blockNode="true"
                v-model:selectedKeys="Data.selectedKeys"
                checkStrictly
                :key="Data.treeHeigh"
                :height="Data.treeHeigh"
                @select="treeSelect"
              >
                <template #title="record">
                  <div class="flex w-full">
                    <span
                      class="flex-1"
                      :class="
                        record.editStatus === 1
                          ? 'line-through text-gray-400'
                          : record.editStatus === 2
                          ? 'text-red-500'
                          : record.editStatus === 3
                          ? 'text-blue-500'
                          : ''
                      "
                    >
                      <span v-if="record.sfwmk === 0">
                        {{ record.tmbh }} {{ record.tmbt }} ({{ record.tmlx }})
                      </span>
                      <span v-else>{{ record.tmbh }} {{ record.mkmc }}</span>
                    </span>

                    <a-tooltip
                      :key="'#fadfvf'"
                      :title="
                        record.editStatus === 1
                          ? '已删除'
                          : record.handlTip
                          ? record.handlTipMsg
                          : '已完成'
                      "
                      :color="'#fadfvf'"
                    >
                      <a-button
                        :danger="record.handlTip"
                        type="link"
                        size="small"
                        :disabled="record.editStatus === 1"
                        :class="record.handlTip || record.editStatus === 1 ? '' : '!text-green-500'"
                      >
                        <ExclamationCircleOutlined v-if="record.handlTip" />
                        <CheckCircleOutlined v-else />
                      </a-button>
                    </a-tooltip>
                    <a-button
                      danger
                      type="link"
                      title="新增子题"
                      size="small"
                      :disabled="
                        record.editStatus === 1 ||
                        (record.editStatus === 3 && !record.draftId) ||
                        (!!record.sfzxdtdw && record.sfwmk === 0) ||
                        isJdCorrectType(record)
                      "
                      @click.stop="addStructure(record)"
                    >
                      <PlusCircleOutlined />
                    </a-button>
                    <a-button
                      danger
                      type="link"
                      title="删除试题"
                      size="small"
                      :disabled="record.editStatus === 1 || isJdCorrectType(record)"
                      @click.stop="handelDelete(record)"
                    >
                      <DeleteOutlined />
                    </a-button>
                    <a-button
                      danger
                      type="link"
                      title="还原"
                      size="small"
                      v-if="record.editStatus !== 3"
                      @click.stop="releaseFun(record)"
                    >
                      <LogoutOutlined />
                    </a-button>
                  </div>
                </template>
              </a-tree>
            </div>
            <a-button type="primary ml-8px" size="small" @click="addStructure()">
              新增题干/模块
            </a-button>
          </div>
        </a-col>
        <a-col :span="16" v-if="!Data.secondBloon">
          <div class="infobox !px-2 overflow-y-auto">
            <midelEdit :isBatchHasObj="Data.treedataObj" @success="mideFunSuccess" />
          </div>
        </a-col>
        <a-col :span="16" v-if="Data.secondBloon">
          <div class="infobox !px-2 overflow-y-auto">
            <setEdit
              :isBatchHasObj="Data.treedataObj"
              @success="mideFunSuccess"
              :fileListProps="teacherOptions"
              @cancel-fun="Data.secondBloon = false"
            />
          </div>
        </a-col>
      </a-row>
    </div>

    <newadd
      v-model:otherShowble="Data.otherShowble"
      :is-batch-has-obj="Data.newAddObj"
      @success="loadData"
    />
  </a-card>
</template>

<script setup lang="ts">
import { onMounted, h, computed, reactive, ref, onUnmounted } from 'vue'
import { useList } from '/@/hooks/web/useList'
import { useRoute, useRouter } from 'vue-router'
import midelEdit from './components/midelEdit.vue'
import setEdit from './components/setEdit.vue'
import newadd from './components/newadd.vue'
import { cloneDeep } from 'lodash-es'

const route: any = useRoute()
const router = useRouter()

// 各个弹窗组件以及其他组件
// 判断是否是机读题
import { isJdCorrectType } from './index'

import { getHasTeachee } from '/@/api/organization/subjectManage'
import {
  getAbnormityTeacher,
  setrevokeSaveTxjgDraft,
  setDelTxjgDraft,
  getDelTxjgDraft,
  getUpdateTxjgDraft,
  getSaveTxjgDraft,
  setUpdateTxjgDraft,
  setSaveTxjgDraft,
  getAcountmdm,
  setApplyTxjg,
} from '/@/api/examinationAudit'

// 消息提示框
import { useMessage } from '/@/hooks/web/useMessage'
const { createMessage, createConfirm } = useMessage()
// 本地存储
import { useUserStore } from '/@/store/modules/user'
const userStore = useUserStore()
const userInfo = computed(() => userStore.getUserInfo)

const Data = reactive<any>({
  statuTypeBloon: false, //是否可以操作应用
  treedataObj: {}, // 选中的树节点对象
  revokeDraftList: [], // 撤销草稿对象
  selectedKeys: [], // 选中的树节点删除
  delList: [], // 删除的试题
  delNunber: 0, // 删除的试题数量
  saveList: [], // 保存的试题
  saveNunber: 0, // 保存的试题数量
  updateList: [], // 修改的试题
  updateNunber: 0, // 修改的试题数量
  originalScore: 0, // 原始总分
  totalScore: 0, // 总分
  totalErrNum: 0, // 试题设置未完车错误数量
  otherShowble: false, // 其他弹窗
  newAddObj: {}, // 新增弹窗
  secondBloon: false, // 是否第二部
  isCanBeApplied: false, // 是否可以应用
  isDistribuState: false, // 分配不合理合理
  treeHeigh: 100, // 树的高度
} as any)

// 选择树节点触法
const treeSelect = (rcode, e) => {
  if (checkNewBool()) return (Data.selectedKeys = [newAddStrId.value])
  let row = e.node.dataRef
  if (Data.treedataObj.id == row.id) {
    Data.treedataObj = {}
  } else {
    let sjSfwmk = flatten(list.value).find(item => item.id == row.sjtmid)?.sfwmk
    Data.treedataObj = filterChild(cloneDeep({ ...row, sjSfwmk }))
    Data.secondBloon = false
  }
}
let { list, loadData, reset } = <any>useList(getAbnormityTeacher, {
  defaultFilterOption: <any>{
    kmdm: route.query.kmdm,
    pySzInfoFlag: true,
  },
  requestSuccess: async (result: any) => {
    if (result.code != 200) {
      createMessage.error(result.message)
    } else {
      Data.originalScore = list.value.reduce((a, b) => a + (b.tmfz || 0), 0)
      Data.treedataObj = {}
      Data.selectedKeys = []
      Data.secondBloon = false
      await getPageDelList()
      await getPageUpdateList()
      await getSaveTxjgDraftList()
      Data.isCanBeApplied = false
      Data.isDistribuState = false
      let { subAll, errNum } = arrangeabnormal(list.value)
      Data.totalScore = subAll
      Data.totalErrNum = errNum
    }
  },
})

// 判断是否设置评阅标准
function arrangeabnormal(arr) {
  let errNum = 0 /** 错误数量 */
  let subAll = 0 /** 子题总分 */
  let subArr: any = [] /** 子题列表数量 */
  for (let i = 0; i < arr.length; i++) {
    let record = arr[i]
    record.tmfz = Number(record.tmfz)
    /**
     * editStatus 0：未编辑，1: 删除，2：修改，3：新增
     */
    if (!record.editStatus) record.editStatus = 0
    // 新增的题目
    if (Data.saveList.length) {
      Data.isCanBeApplied = true
      Data.saveList.sort((a, b) => a.tmxh - b.tmxh)
    }
    for (let j = 0; j < Data.saveList.length; j++) {
      const element = Data.saveList[j]
      element.id = element.draftId
      element.editStatus = 3
      if (element.sjtmid == record.id) {
        if (record.children && record.children.length) {
          record.children.push(element)
        } else {
          record.children = [element]
        }
        Data.saveList.splice(j, 1)
        j--
      } else if (element.sjtmid == 0 && record.sjtmid == 0) {
        arr.push(element)
        Data.saveList.splice(j, 1)
        j--
      }
    }

    let {
      errNum: subErrNum,
      subAll: subMinmin,
      subArr: subMinArr,
    } = arrangeabnormal(record.children || [])
    if (!record.handlTip) record.handlTip = false
    record.subArr = subMinArr
    record.subAll = subMinmin
    // 删除的题目
    if (Data.delList.includes(record.id)) {
      Data.isCanBeApplied = true
      record.editStatus = 1
      record.disabled = true
      continue
    }

    // 修改过的题目
    for (let j = 0; j < Data.updateList.length; j++) {
      Data.isCanBeApplied = true
      const element = Data.updateList[j]
      if (element.id == record.id) {
        record.editStatus = 2
        arr[i] = {
          ...record,
          ...element,
          children: record.children || [],
        }
        record = arr[i]

        Data.updateList.splice(j, 1)
        break
      }
    }

    subArr.push(record)
    subAll += record.sfzxdtdw === 1 ? record.tmfz : +record.subAll

    if (record.subAll != record.tmfz && record.sfzxdtdw === 0) {
      Data.isDistribuState = true
    }

    if (subMinArr.length) {
      // 判断子题是否设置评阅模式
      errNum += subErrNum
      if (subErrNum > 0) {
        record.handlTip = true
        record.handlTipMsg = '子题设置不完整。'
        errNum += 1
      }
      // 判断子题分数和是否和父题分数相等
      if (subMinmin != record.tmfz) {
        record.handlTip = true
        record.handlTipMsg = '子题目分值和与父题目分值不相等。'
        errNum += 1
      }
      /** 机读题 */ /** 疑问 当时机读题时父体是之前的题目已经分配过评阅教师.新增的子题还需要分配评阅教师吗 */
      if (
        (isJdCorrectType(record) || record.tmlx === '填空题') &&
        subMinArr[0].sfzxdtdw === 1 &&
        record.sfwmk == 0
      ) {
        if (!record.pySzInfoVO?.pySzJsfpList || !record.pySzInfoVO?.pySzJsfpList?.length) {
          record.handlTip = true
          record.handlTipMsg = '试题还未分配评阅教师'
          errNum += 1
        }
        for (let j = 0; j < subMinArr.length; j++) {
          if (
            !record.pySzInfoVO?.pySzCkdaList ||
            !record.pySzInfoVO?.pySzCkdaList.length ||
            !record.pySzInfoVO?.pySzCkdaList.find(item => item.stId == subMinArr[j].id)
          ) {
            subMinArr[j].handlTip = true
            subMinArr[j].handlTipMsg = '未设置参考答案'
            errNum += 1
            record.handlTip = true
            record.handlTipMsg = '参考答案设置不完整'
          }
        }
      }
    } else if (!isJdCorrectType(record) && record.tmlx != '填空题' && record.sfzxdtdw === 1) {
      // 非机读题设置情况
      if (!record.pySzInfoVO?.zpFc) {
        record.handlTip = true
        record.handlTipMsg = '自评允许最大分差(含)不能为空。'
        errNum += 1
      } else if (!record.pySzInfoVO?.pySzCkdaList.length) {
        record.handlTip = true
        record.handlTipMsg = '试题还未设置参考答案'
        errNum += 1
      } else if (!record.pySzInfoVO?.pySzJsfpList.length) {
        record.handlTip = true
        record.handlTipMsg = '试题还未分配评阅教师'
        errNum += 1
      } else if (!record.tmfz) {
        record.handlTip = true
        record.handlTipMsg = '题目得分不能为空'
        errNum += 1
      } else if (!record.pySzInfoVO?.pydfgc) {
        record.handlTip = true
        record.handlTipMsg = '最小得分单位不能为空'
        errNum += 1
      } else if (+record.pySzInfoVO?.zpFc > +record.tmfz) {
        record.handlTip = true
        record.handlTipMsg = '自评允许最大分差(含)大于试题分值。'
        errNum += 1
      } else if (record.pySzInfoVO?.pyMs == '2' && +record.pySzInfoVO?.spFc > +record.tmfz) {
        record.handlTip = true
        record.handlTipMsg = '双评分差大于试题分值。'
        errNum += 1
      } else if (+record.pySzInfoVO?.pydfgc % 0.5) {
        record.handlTip = true
        record.handlTipMsg = '最小得分单位不是0.5的整数倍。'
        errNum += 1
      } else if (record.tmfz % +record.pySzInfoVO?.pydfgc) {
        record.handlTip = true
        record.handlTipMsg = '试题分值不是最小得分单位的整数倍。'
        errNum += 1
      } else if (record.pySzInfoVO?.pyMs == '2' && record.pySzInfoVO?.existsPyFpjsCount < 2) {
        record.handlTip = true
        record.handlTipMsg = '双评模式下至少分配两名教师'
        errNum += 1
      } else if (record.pySzInfoVO?.pySzDfdList && record.pySzInfoVO?.pySzDfdList.length) {
        let number = 0
        for (let j = 0; j < record.pySzInfoVO?.pySzDfdList.length; j++) {
          if (record.pySzInfoVO?.pySzDfdList[j].dfdScore % +record.pySzInfoVO?.pySzInfoVO?.pydfgc) {
            record.handlTip = true
            record.handlTipMsg = '试题得分点分值不能被最小得分单位整除。'
            errNum += 1
            break
          }
          number += +record.pySzInfoVO?.pySzDfdList[j]?.dfdScore
        }
        if (number != record.tmfz) {
          record.handlTip = true
          record.handlTipMsg = '试题得分点的分值和试题的分值不相等。'
          errNum += 1
        }
      } else if (!record.pySzInfoVO?.pyMs) {
        record.handlTip = true
        record.handlTipMsg = '试题未设置评阅模式'
        errNum += 1
      }
    } else if (record.sfzxdtdw === 0 && !record.subArr.length) {
      record.handlTip = true
      record.handlTipMsg = '请添加设置子题'
      errNum += 1
    }
  }
  return {
    errNum,
    subAll,
    subArr,
  }
}

// 重置设置
const releaseFun = async (record: any = {}) => {
  if (!!record.id && checkNewBool()) return
  createConfirm({
    iconType: 'warning',
    title: () => h('span', '温馨提醒'),
    getContainer: '.layout-card',
    closable: true,
    content: () =>
      h(
        'span',
        record.id
          ? `确认还原当对前试题${
              record.children && record.children.length ? '及子题' : ''
            }的编辑吗？`
          : '确认还原全部试题的编辑吗？'
      ),
    cancelText: record.children && record.children.length ? '还原当前试题及子题' : '取消',
    okText: record.id ? '还原当前试题' : '全部还原',
    onOk: async () => {
      createDialog(record)
    },
    onCancel: async e => {
      if (!e?.triggerCancel && record.children && record.children.length) {
        createDialog(record, true)
      }
    },
  })
}

// 试题还原弹窗
function createDialog(record: any = {}, nextType: boolean = false) {
  let revokeDraftList: any = []
  if (record.id) {
    if (record.editStatus !== 0) revokeDraftList = [{ id: record.id, draftId: record.draftId }]
    if (record.editStatus === 1 && record.sjtmid) {
      revokeDraftList = getParantList(record.id)
        ?.filter(item => item.editStatus === 1)
        ?.map(item => ({ id: item.id }))
    }
    if (nextType) {
      let nextList = getChildIdList(record.children || [])
      revokeDraftList = revokeDraftList.concat(
        nextList
          .filter(item => item.editStatus !== 0)
          .map(item => {
            if (item.editStatus === 1) {
              return { id: item.id }
            } else if (item.editStatus === 2) {
              return { id: item.id, draftId: item.draftId }
            } else if (item.editStatus === 3) {
              return { draftId: item.draftId }
            }
          }) || []
      )
    }
  }
  pageSaveTxjgDraft(!record.id, revokeDraftList)
}

// 重置远程方法
async function pageSaveTxjgDraft(
  resetAllFlag = false,
  revokeDraftList: any = [],
  getLoadData = true
) {
  if (revokeDraftList.length === 0 && !resetAllFlag) return createMessage.info('操作成功')
  let { code, message } = await setrevokeSaveTxjgDraft({
    kmdm: route.query.kmdm,
    sjlb: route.query?.sjlb,
    revokeDraftList,
    resetAllFlag, //当为true时，revokeDraftList无意义
  })
  if (code == 200) {
    createMessage.info('操作成功')
    getLoadData && loadData()
  } else {
    createMessage.error(message)
  }
}

// 应用试题结构
const releaseSetBreakTest = async () => {
  if (checkNewBool()) return
  if (!Data.isCanBeApplied) {
    createMessage.warning('当前试题结构未作任何修改，请先修改试题结构再应用')
    return
  }
  if (Data.isDistribuState) {
    createMessage.warning('当前试题结构题设置题目分值目分配不合理，请从新分配设置')
    return
  }
  // if (Data.totalScore != Data.originalScore) {
  //   createMessage.warning('试题总分与原始试题总分不一致，请先修改试题并设置试题结构及试题得分')
  //   return
  // }
  if (!!Data.totalErrNum) {
    createMessage.error('试题设置未完成,请先完成试题设置')
    return
  }
  let { code, data } = await getAcountmdm({
    kmdm: route.query.kmdm,
  })
  if (code === 200) {
    let tiemNubOkText = ref('确认(5S)')
    let tiemnum = 5
    let timer = setInterval(() => {
      tiemnum--
      tiemNubOkText.value = `确认(${tiemnum}S)`
      if (tiemnum === 0) {
        tiemNubOkText.value = '确认'
        clearInterval(timer)
      }
      confirmModel.update({
        okText: tiemNubOkText.value,
        okButtonProps: {
          disabled: tiemnum >= 1,
        },
      })
    }, 1000)
    let confirmModel: any = createConfirm({
      iconType: 'warning',
      okButtonProps: {
        disabled: !!tiemnum,
      },
      okText: tiemNubOkText.value,
      title: () => h('span', '温馨提醒'),
      content: () =>
        h(
          'span',
          `请确认是否应用!${
            data.kmpyjd === 'TEST' || data.kmpyjd === 'FORMAL'
              ? '当前科目处于评阅阶段，应用后将重置涉及到调整试题的评阅进度'
              : ''
          }`
        ),
      onOk: async () => {
        let { code, message } = await setApplyTxjg({
          kmdm: route.query.kmdm,
          sjlb: route.query?.sjlb,
        })
        if (code === 200) {
          createMessage.info('操作成功')
          router.back()
        } else {
          createMessage.error(message)
        }
      },
    })
  }
}

const newAddStrId = ref('')
// 新增试题结构/模块
function addStructure(row: any = {}) {
  if (checkNewBool()) return
  let obj: any = {
    id: +new Date(),
    editStatus: 3,
    children: [],
    tmlx: '填空题',
    tmbt: '新增试题',
    tmfz: null,
    xxsl: null,
    sjtmid: '0',
    sfzxdtdw: 0,
    tmxh: null,
    sfwmk: 1,
    mkmc: '新增模块',
    tmbh: '',
    pySzInfoDraft: {},
    sfmkDisabled: true, //前端状态控制是否可编辑模块
    sjSfwmk: undefined,
  }
  newAddStrId.value = obj.id
  if (!row.id) {
    obj.sjtmid = 0
    obj.tmxh = list.value?.length ? list.value[list.value?.length - 1].tmxh + 1 : 1
    list.value.push(obj)
    Data.selectedKeys = [obj.id]
    Data.treedataObj = obj
  } else {
    let revokeDraftList = getParantList(row.id)
    Data.newAddObj = revokeDraftList[revokeDraftList.length - 1]
    Data.otherShowble = true
  }
}
// 校验是否有新增的题干/模块
function checkNewBool() {
  let newAddObj =
    list.value.find((item: any) => {
      return item.id === newAddStrId.value
    }) || {}
  if (newAddObj.id) {
    createMessage.warning('请先保存新增题干/模块')
    return true
  } else {
    return false
  }
}

// 删除试题结构
function handelDelete(record: any) {
  if (record.id != newAddStrId.value && checkNewBool()) return
  createConfirm({
    iconType: 'warning',
    title: () => h('span', '温馨提醒'),
    content: () =>
      h(
        'span',
        `您确定删除当前试题${
          record.subArr && record.subArr.length ? '及子题或当前试题的所有子题' : ''
        }吗？`
      ),
    okText: `删除当前试题${record.subArr && record.subArr.length ? '及子题' : ''}`,
    getContainer: '.layout-card',
    closable: true,
    cancelText: record.subArr && record.subArr.length ? '仅删除子题' : '取消',
    onOk: async () => {
      longRangeDel(record, record.id)
    },
    onCancel: async e => {
      if (!e?.triggerCancel && record.subArr && record.subArr.length) {
        longRangeDel(record)
      }
    },
  })
}

/**
 * 删除远程方法
 */

async function longRangeDel(record, id: any = null) {
  let childrenList = getChildIdList(record.children || [])
  let delDraftList =
    childrenList
      .filter(item => item.editStatus !== 3 && item.editStatus !== 1)
      .map(item => item.id) || []

  let reseList =
    childrenList
      .filter(item => item.editStatus === 3 && item.draftId)
      .map(item => ({ draftId: item.id })) || []

  if (id) {
    if (record.editStatus === 3) {
      if (record.draftId) {
        reseList.push({ draftId: id })
      }
    } else {
      delDraftList.push(id)
    }
  }
  if (reseList.length) {
    await pageSaveTxjgDraft(false, reseList, false)
  }
  if (delDraftList.length) {
    let { code, message } = await setDelTxjgDraft({
      kmdm: route.query.kmdm,
      sjlb: route.query?.sjlb,
      delDraftList,
    })
    if (code == 200) {
      createMessage.info('删除成功')
    } else {
      createMessage.error(message)
    }
  }

  loadData()
}

/**
 * 获取所有子题的IdList
 */

function getChildIdList(data: any = []) {
  let idList: any = []
  data.forEach((item: any) => {
    idList.push(item)
    if (item.children && item.children.length > 0) {
      idList.push(...getChildIdList(item.children || []))
    }
  })
  return idList
}

/**
 * 拉平数数组
 */

function flatten(arr: any) {
  return arr.reduce((result, item) => {
    return result.concat(item, Array.isArray(item.children) ? flatten(item.children) : [])
  }, [])
}
/**
 * 获取父节点列表
 */
function getParantList(id) {
  let lislArr = flatten(list.value)
  let parantList: any = []
  for (let i = 0; i < lislArr.length; i++) {
    if (id == lislArr[i].id) {
      if (lislArr[i].sjtmid != 0) {
        parantList = getParantList(lislArr[i].sjtmid)
      }
      parantList.push(lislArr[i])
      break
    }
  }

  return parantList
}

// 获取已经删除的试题结构
async function getPageDelList() {
  let { code, data, message } = await getDelTxjgDraft({
    kmdm: route.query.kmdm,
    sjlb: route.query?.sjlb,
  })
  if (code == 200) {
    Data.delList = data
    Data.delNunber = data.length
  } else {
    createMessage.error(message)
  }
}

// 获取已近修改的试题结构
async function getPageUpdateList() {
  let { code, data, message } = await getUpdateTxjgDraft({
    kmdm: route.query.kmdm,
    sjlb: route.query?.sjlb,
  })
  if (code == 200) {
    Data.updateList = data
    Data.updateNunber = data.length
  } else {
    createMessage.error(message)
  }
}

// 获取新增的试题结构
async function getSaveTxjgDraftList() {
  let { code, data, message } = await getSaveTxjgDraft({
    kmdm: route.query.kmdm,
    sjlb: route.query?.sjlb,
  })
  if (code == 200) {
    Data.saveList = data
    Data.saveNunber = data.length
  } else {
    createMessage.error(message)
  }
}

/**
 * 过滤可用子级
 */
function filterChild(row: any) {
  if (row?.children?.length) {
    row.children = row.children.filter((item: any) => item.editStatus !== 1)
    for (let i = 0; row?.children.length > i; i++) {
      filterChild(row.children[i])
    }
  }
  return row
}

//查询可分配教师
const teacherOptions: any = ref([])
const getTeacherOptions = async () => {
  let { code, data } = await getHasTeachee({
    kmdm: route.query.kmdm,
  })
  if (code == 200) {
    for (let key in data) {
      teacherOptions.value.push({
        label: `${data[key]}(${key})`,
        value: key,
        account: key,
        jsxm: data[key],
        kmdm: route.query.kmdm,
        sysYear: userInfo.value?.kmYear,
      })
    }
  }
}

// 保存编辑结果
async function mideFunSuccess(e, pySzInfoVO: any = {}) {
  if (e) {
    Data.secondBloon = e
  } else {
    let editObj = cloneDeep({
      ...Data.treedataObj,
      pySzInfoVO: pySzInfoVO.pyMs ? pySzInfoVO : Data.treedataObj?.pySzInfoVO,
      children: [],
    })

    let updateDraftList: any = []
    let saveDraftList: any = []
    let allCode: any, allMessage: any
    let xxsl =
      editObj.sfwmk === 0
        ? editObj?.tmlx == '单项选择题' || editObj?.tmlx == '多项选择题'
          ? editObj?.xxsl
          : editObj?.tmlx === '判断题'
          ? 2
          : 0
        : 0

    if (editObj?.tmlx == '多项选择题') {
      editObj?.pySzInfoVO?.pySzCkdaList.forEach((item: any) => {
        item.ckda = item?.ckda?.join(',') || ''
      })
    }

    if (editObj.editStatus === 3) {
      saveDraftList.push({
        ...editObj,
        id: undefined,
        xxsl,
        tmlx: editObj.sfwmk == 1 ? '' : editObj.tmlx,
      })
    } else {
      updateDraftList.push({
        ...editObj,
        xxsl,
        tmlx: editObj.sfwmk == 1 ? '' : editObj.tmlx,
      })
    }

    if (Data.secondBloon && Data.treedataObj?.children && Data.treedataObj?.children.length) {
      for (let i = 0; i < Data.treedataObj?.children.length; i++) {
        let findObj = editObj?.pySzInfoVO?.pySzCkdaList.find(
          item => item.stId === Data.treedataObj?.children[i].id
        )
        if (findObj?.tmfz !== Data.treedataObj?.children[i]?.tmfz) {
          Data.treedataObj.children[i].tmfz = findObj.tmfz
          if (Data.treedataObj?.children[i].editStatus === 3) {
            saveDraftList.push({
              ...Data.treedataObj?.children[i],
              id: undefined,
              children: [],
            })
          } else {
            updateDraftList.push({
              ...Data.treedataObj?.children[i],
              children: [],
            })
          }
        }
      }
    }

    if (updateDraftList.length) {
      let { code, message } = await setUpdateTxjgDraft({
        kmdm: route.query.kmdm,
        sjlb: route.query.sjlb,
        updateDraftList,
      })
      allCode = code
      allMessage = message
    }

    if (saveDraftList.length) {
      let { code, message } = await setSaveTxjgDraft({
        kmdm: route.query.kmdm,
        sjlb: route.query.sjlb,
        saveDraftList,
      })
      allCode = code
      allMessage = message
    }

    if (allCode === 200) {
      createMessage.success('保存成功')
      loadData()
    } else {
      createMessage.error(allMessage)
    }
  }
}

const treeReefbox = ref<any>(null)

function resize() {
  Data.treeHeigh = treeReefbox.value?.offsetHeight
}

onMounted(async () => {
  getTeacherOptions('')
  window?.addEventListener('resize', resize)
  setTimeout(() => {
    resize()
  }, 100)
})

onUnmounted(() => {
  window?.removeEventListener('resize', resize)
})
</script>

<style lang="less" scoped>
.layout-card {
  min-height: calc(@c_height + 32px);

  .claserbox {
    border: 1px solid #e8e8e8;
    margin-top: 10px;
    .infobox {
      width: 100%;
      height: calc(100vh - 180px);
      min-height: 300px;
      border-left: 1px solid #e8e8e8;
      padding: 10px 0;
      overflow-y: auto;
      font-size: 15px;
      .treebox {
        height: calc(100% - 40px);
        overflow-y: auto;
        ::v-deep(.ant-tree-checkbox-disabled .ant-tree-checkbox-inner) {
          background-color: #e8e8e8;
        }
        ::v-deep(.ant-tree-checkbox-inner) {
          border: 2px solid #d9d9d9;
        }
      }
    }
  }

  ::v-deep(.ant-modal-close-x) {
    color: rgba(0, 0, 0, 0.45) !important;
  }
}
</style>
